package com.djhu.es.core.config;
/**
 * Created by zw on 2017/12/28.
 */

import com.djhu.es.core.ClientSource;
import com.djhu.es.core.ClientSourcePool;
import com.djhu.es.core.ElasticsearchTemplate;
import com.djhu.es.core.SingleClientSource;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * <p>
 * ---------------------------------
 */
@Configuration
@EnableConfigurationProperties(ElasticsearchProperties.class)
@ConditionalOnClass(value = {PreBuiltTransportClient.class})
@ConditionalOnProperty(prefix = "spring.boot.djhu.elasticsearch", value="enabled", matchIfMissing =false )
public class ElasticsearchAutoConfig {
    @Autowired
    private ElasticsearchProperties elasticsearchProperties;

    @Bean(destroyMethod = "destory")
    public ClientSource clientSource(){
        if (elasticsearchProperties.getPooled().equals("pooled")){
            GenericObjectPool.Config config = new GenericObjectPool.Config();
            return new ClientSourcePool(config, elasticsearchProperties.getHost(),elasticsearchProperties.getPort());
        }else {
            return  new SingleClientSource(elasticsearchProperties.getHost(),elasticsearchProperties.getPort());
        }
    }

    @Bean
    public ElasticsearchTemplate elasticsearchTemplate(ClientSource clientSource){
        return new ElasticsearchTemplate(clientSource);
    }

}